package com.example;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserServiceI {
    private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private UserCache cache;

    private List<User> users = new ArrayList<>();

    @Override
    public boolean login(String userName, String password) {
        cache.setUserName(userName);
        cache.setLoginTime(new Date());
        logger.info("登录人：" + userName + "，登录时间：" + cache.getLoginTime());
        return true;
    }

    @Override
    public boolean logout() {
        String userName = cache.getUserName();
        Date loginTime = cache.getLoginTime();
        cache.setUserName(null);
        cache.setLoginTime(null);
        logger.info("登录人：" + userName + "，本次使用时间：" + (new Date().getTime() - loginTime.getTime()) + "毫秒");
        return true;
    }

    @Override
    public void addUser(User user) {
        users.add(user);
        logger.info("添加用户成功");
    }

    @Override
    public void updateUser(User user) {
        for (User u : users) {
            if (u.getUserName().equals(user.getUserName())) {
                u.setAge(user.getAge());
                u.setMobile(user.getMobile());
                u.setEmail(user.getEmail());
                break;
            }
        }
        logger.info("更新用户成功");
    }

    @Override
    public void deleteUser(String userName) {
        users.removeIf(user -> user.getUserName().equals(userName));
        logger.info("删除用户成功");
    }
}